﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;

namespace PageAdmin.Utils
{
    /// <summary>
    /// AwinRar帮助类
    /// </summary>
    public class WinRarHelper
    {

        private static bool ExistsWinRar(out string winRarPath)
        {
            winRarPath = String.Empty;
            //通过Regedit（注册表）找到WinRar文件
            var registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
            if (registryKey == null) return false;//未安装
                                                  //registryKey = theReg;可以直接返回Registry对象后面操作
            winRarPath = registryKey.GetValue("").ToString();
            //这里为节约资源，直接返回路径，反正下面也没用到
            registryKey.Close();//关闭注册表
            return !String.IsNullOrEmpty(winRarPath);
        }

        /// <summary>
        /// 生成压缩文件
        /// </summary>
        /// <param name="compressPath"></param>
        /// <param name="zipPath"></param>
        public static void Compress(string compressPath, string zipPath)
        {
            try
            {
                zipPath = IOHelper.MapPath(zipPath);
                string zipName = Path.GetFileName(zipPath);
                string zipDirectory = zipPath.Replace(zipName, "");
                String winRarPath = null;
                //if (!ExistsWinRar(out winRarPath)) //不存在则用框架自带的
                //{
                //    ZipHelper.Compress(compressPath, zipPath);
                //    return;
                //}
                var pathInfo = string.Format("a -afzip -m2 -ep1 \"{0}\" \"{1}\"", zipName, compressPath);
                #region WinRar 用到的命令注释
                //[a] 添加到压缩文件
                //afzip 执行zip压缩方式，方便用户在不同环境下使用。
                //（取消该参数则执行rar压缩）
                //-m0 存储 添加到压缩文件时不压缩文件。共6个级别【0-5】，值越大效果越好，也越慢
                //ep1 依名称排除主目录（生成的压缩文件不会出现不必要的层级）
                //r 修复压缩档案
                //t 测试压缩档案内的文件
                //as 同步压缩档案内容 
                //-p 给压缩文件加密码方式为：-p123456
                #endregion
                //打包文件存放目录
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = winRarPath,//执行的文件名
                    Arguments = pathInfo,//需要执行的命令
                    UseShellExecute = true,//使用默认启动程序执行
                    WindowStyle = ProcessWindowStyle.Hidden,//隐藏窗体
                    WorkingDirectory = zipDirectory,//rar 存放位置
                    CreateNoWindow = false,//不显示窗体

                };
                string outPut, error;
                CmdHelper.RunCmd(startInfo, out outPut, out error);
                if(!string.IsNullOrEmpty(error))
                {
                    throw new Exception(error);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="deDirectory"></param>
        /// <param name="zipPath"></param>
        /// <returns></returns>
        public static void DeCompress(string zipPath, string deDirectory)
        {
            try
            {
                zipPath = IOHelper.MapPath(zipPath);
                string zipName = Path.GetFileName(zipPath);
                string zipDirectory = zipPath.Replace(zipName, "");
                String winRarPath = null;
                if (!ExistsWinRar(out winRarPath)) //不存在则用框架自带的
                {
                    ZipHelper.DeCompress(zipPath,deDirectory);
                    return;
                }
                if (Directory.Exists(deDirectory) == false)
                {
                    IOHelper.CreateDirectory(deDirectory);
                }
                var pathInfo = "x " + zipName + " " + deDirectory + " -y";

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = winRarPath,//执行的文件名
                    Arguments = pathInfo,//需要执行的命令
                    UseShellExecute = true,//使用默认启动程序执行
                    WindowStyle = ProcessWindowStyle.Hidden,//隐藏窗体
                    WorkingDirectory = zipDirectory,//rar 存放位置
                    CreateNoWindow = false,//不显示窗体
                };

                string outPut, error;
                CmdHelper.RunCmd(startInfo,out outPut, out error);
                if (!string.IsNullOrEmpty(error))
                {
                    throw new Exception(error);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


    }
}
